package com.project.demo.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息通知服务
 * 用于统一创建和管理用户消息通知
 */
@Slf4j
@Service
public class MessageNotificationService {

    @Autowired
    private com.project.demo.service.impl.UserMessageServiceImpl userMessageService;

    /**
     * 检查字符串是否为双语JSON格式
     */
    private boolean isBilingualJson(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        try {
            JSONObject json = JSONObject.parseObject(str);
            return json != null && json.containsKey("zh") && json.containsKey("en");
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 确保字段是双语JSON格式，如果不是则尝试转换
     */
    private String ensureBilingualJson(String value, String defaultZh) {
        if (value == null || value.isEmpty()) {
            return null;
        }
        // 如果已经是双语JSON格式，直接返回
        if (isBilingualJson(value)) {
            return value;
        }
        // 如果不是，尝试创建双语JSON格式（假设当前值是中文）
        try {
            JSONObject json = new JSONObject();
            json.put("zh", value);
            json.put("en", defaultZh != null ? defaultZh : value); // 如果没有英文，使用中文作为默认值
            return json.toJSONString();
        } catch (Exception e) {
            // 如果转换失败，返回原值
            return value;
        }
    }

    /**
     * 创建住宿消息通知
     */
    public void createAccommodationMessage(Integer userId, Integer accommodationId, 
                                           String conferenceName, String accommodationLocation, 
                                           String accommodationNo, String userName) {
        try {
            Map<String, Object> messageData = new HashMap<>();
            messageData.put("user_id", userId);
            messageData.put("message_type", "accommodation");
            messageData.put("title", "住宿安排通知");
            
            StringBuilder content = new StringBuilder();
            content.append("您好 ").append(userName != null ? userName : "").append("，\n\n");
            content.append("您的住宿安排已确认：\n");
            
            // 确保会议名称是双语JSON格式
            if (conferenceName != null && !conferenceName.isEmpty()) {
                String bilingualConferenceName = ensureBilingualJson(conferenceName, null);
                content.append("会议：").append(bilingualConferenceName).append("\n");
            }
            
            // 确保住宿地点是双语JSON格式
            if (accommodationLocation != null && !accommodationLocation.isEmpty()) {
                String bilingualLocation = ensureBilingualJson(accommodationLocation, null);
                content.append("住宿地点：").append(bilingualLocation).append("\n");
            }
            
            if (accommodationNo != null && !accommodationNo.isEmpty()) {
                content.append("房间号：").append(accommodationNo).append("\n");
            }
            content.append("\n请按时入住，如有疑问请联系会务组。");
            
            messageData.put("content", content.toString());
            messageData.put("related_id", accommodationId);
            messageData.put("is_read", 0);
            messageData.put("create_time", new Timestamp(System.currentTimeMillis()));
            messageData.put("update_time", new Timestamp(System.currentTimeMillis()));

            userMessageService.insert(messageData);
            log.info("创建住宿消息通知成功 - userId: {}, accommodationId: {}", userId, accommodationId);
        } catch (Exception e) {
            log.error("创建住宿消息通知失败", e);
        }
    }

    /**
     * 创建通知消息
     */
    public void createNotificationMessage(Integer userId, Integer notificationId,
                                         String conferenceName, String notificationContent,
                                         String userName) {
        try {
            Map<String, Object> messageData = new HashMap<>();
            messageData.put("user_id", userId);
            messageData.put("message_type", "notification");
            messageData.put("title", "会议通知");
            
            StringBuilder content = new StringBuilder();
            content.append("您好 ").append(userName != null ? userName : "").append("，\n\n");
            content.append("您有新的会议通知：\n\n");
            
            // 通知内容可能是双语JSON格式，保持原样
            if (notificationContent != null && !notificationContent.isEmpty()) {
                content.append(notificationContent).append("\n\n");
            }
            
            // 确保会议名称是双语JSON格式
            if (conferenceName != null && !conferenceName.isEmpty()) {
                String bilingualConferenceName = ensureBilingualJson(conferenceName, null);
                content.append("会议：").append(bilingualConferenceName);
            }
            content.append("\n\n请及时查看详情。");
            
            messageData.put("content", content.toString());
            messageData.put("related_id", notificationId);
            messageData.put("is_read", 0);
            messageData.put("create_time", new Timestamp(System.currentTimeMillis()));
            messageData.put("update_time", new Timestamp(System.currentTimeMillis()));

            userMessageService.insert(messageData);
            log.info("创建通知消息成功 - userId: {}, notificationId: {}", userId, notificationId);
        } catch (Exception e) {
            log.error("创建通知消息失败", e);
        }
    }

    /**
     * 创建排座消息通知
     */
    public void createSeatMessage(Integer userId, Integer seatArrangementId,
                                  String conferenceName, String seatNumber,
                                  String meetingVenue, String userName) {
        try {
            Map<String, Object> messageData = new HashMap<>();
            messageData.put("user_id", userId);
            messageData.put("message_type", "seat");
            messageData.put("title", "座位安排通知");
            
            StringBuilder content = new StringBuilder();
            content.append("您好 ").append(userName != null ? userName : "").append("，\n\n");
            content.append("您的座位安排已确认：\n");
            
            // 确保会议名称是双语JSON格式
            if (conferenceName != null && !conferenceName.isEmpty()) {
                String bilingualConferenceName = ensureBilingualJson(conferenceName, null);
                content.append("会议：").append(bilingualConferenceName).append("\n");
            }
            
            if (seatNumber != null && !seatNumber.isEmpty()) {
                content.append("座位号：").append(seatNumber).append("\n");
            }
            
            // 确保会议地点是双语JSON格式
            if (meetingVenue != null && !meetingVenue.isEmpty()) {
                String bilingualVenue = ensureBilingualJson(meetingVenue, null);
                content.append("会议地点：").append(bilingualVenue).append("\n");
            }
            content.append("\n请按座位号就座，感谢配合。");
            
            messageData.put("content", content.toString());
            messageData.put("related_id", seatArrangementId);
            messageData.put("is_read", 0);
            messageData.put("create_time", new Timestamp(System.currentTimeMillis()));
            messageData.put("update_time", new Timestamp(System.currentTimeMillis()));

            userMessageService.insert(messageData);
            log.info("创建排座消息通知成功 - userId: {}, seatArrangementId: {}", userId, seatArrangementId);
        } catch (Exception e) {
            log.error("创建排座消息通知失败", e);
        }
    }
}

